package com.qf.system.peilian.controller;

import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.constraints.NotNull;

import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.validation.Errors;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.qf.system.menu.model.Menu;
import com.qf.system.peilian.model.Peilian;
import com.qf.system.peilian.service.PeilianService;
import com.qf.system.timer.model.Timer;
import com.qf.system.timer.service.TimerService;
import com.qf.system.userinfo.service.UserInfoService;
import com.qf.util.AppUtil;
import com.qf.util.ObjectExcelView;
import com.qf.util.PageData;
import com.qf.util.common.Const;
import com.qf.util.common.Tools;
import com.qf.util.controller.BaseController;
import com.qf.util.page.Page;
/** 
 * 类名称：PeilianController
 * 创建人：周广文
 * 创建时间：2015-11-20
 */
@Controller
@RequestMapping(value="/qjqwmain/peilian")
public class PeilianController extends BaseController{
	@Resource(name="peilianService")
	private PeilianService peilianService;
	@Resource(name="timerService")
	private TimerService timerService;
	@Resource(name="userinfoService")
	private UserInfoService userinfoService;
	/**
	 * 新增
	 */
	@RequestMapping(value="/save")
	public ModelAndView save( ) throws Exception{
		logBefore(logger, "新增Peilian");
		ModelAndView mv = this.getModelAndView();
		PageData pd=new PageData();
		pd=this.getPageData();
	Peilian peilian=new Peilian();
	if(Tools.notEmpty(pd.getString("pl_age"))){
		peilian.setPl_age(Integer.parseInt(pd.getString("pl_age")));
	}
    peilian.setPl_jiesao(pd.getString("pl_jiesao"));
    peilian.setPl_job(pd.getString("pl_job"));
    peilian.setPl_name(pd.getString("pl_name"));
    peilian.setPl_photo(pd.getString("pl_photo"));
    peilian.setPl_sex(pd.getString("pl_sex"));
		
			int i=peilianService.save(peilian);
			if(i>0){
				mv.addObject("msg","success");
				mv.setViewName("save_result");
				return mv;
			}else{
				mv.addObject("msg","error");
				mv.setViewName("save_result");
				return mv;
			}
	}
	/**
	 * 删除
	 */
	@RequestMapping(value="/delete")
	public void delete(@NotNull String peilian_id, PrintWriter out){
		logBefore(logger, "删除Peilian");
		try{
		   int i=peilianService.delete(peilian_id);
		   if(i>0){
			out.write("success");
			out.close();
		   }else{
			   out.write("error");
				out.close();
		   }
		} catch(Exception e){
			logger.error(e.toString(), e);
		}
		
	}
	
	/**
	 * 修改
	 */
	@RequestMapping(value="/edit")
	public ModelAndView edit(@Validated @ModelAttribute("peilian") Peilian peilian ,Errors errors) throws Exception{
		logBefore(logger, "修改Peilian");
		ModelAndView mv = this.getModelAndView();
		if(errors.hasErrors()){
			 mv.setViewName("/WEB-INF/system/error/error_all");
	            return mv;  
		}else{
		   int i= peilianService.edit(peilian);
		   if(i>0){
		   mv.addObject("msg","success");
		   mv.setViewName("save_result");
		   return mv;
		   }else{
			   mv.addObject("msg","error");
			   mv.setViewName("save_result");
			   return mv;
		   }
		}
	}
	
	/**
	 * 列表
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value="/list")
	public ModelAndView list(Page page){
		logBefore(logger, "列表Peilian");
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		try{
			pd = this.getPageData();
			
		   this.getHC(); //调用权限
			//////////////////////////////
			Map<String,Object> map = peilianService.list(page,pd);
			page = (Page)map.get("page");
			List<Map<String,Object>> list = (List<Map<String,Object>>)map.get("list");
			mv.addObject("varList", list);
			mv.addObject("pd", pd);
			mv.addObject("page", page);
			mv.setViewName("/WEB-INF/system/peilian/peilian_list");
			
			
		} catch(Exception e){
			logger.error(e.toString(), e);
		}
		return mv;
	}
	@SuppressWarnings("unchecked")
	@RequestMapping(value="/getpeilian")
	public ModelAndView getpeilian(Page page){
		logBefore(logger, "列表Peilian");
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		try{
			pd = this.getPageData();
			
		   this.getHC(); //调用权限
			//////////////////////////////
			Map<String,Object> map = peilianService.list(page,pd);
			page = (Page)map.get("page");
			List<Map<String,Object>> list = (List<Map<String,Object>>)map.get("list");
			mv.addObject("varList", list);
			mv.addObject("pd", pd);
			mv.addObject("page", page);
			mv.setViewName("/WEB-INF/system/peilian/getpeilian");
			
			
		} catch(Exception e){
			logger.error(e.toString(), e);
		}
		return mv;
	}

	
	/**
	 * 去新增页面
	 */
	@RequestMapping(value="/goAdd")
	public ModelAndView goAdd(){
		logBefore(logger, "去新增Peilian页面");
		ModelAndView mv = this.getModelAndView();
		try {
			mv.setViewName("/WEB-INF/system/peilian/peilian_edit");
			mv.addObject("msg", "save");
		} catch (Exception e) {
			logger.error(e.toString(), e);
		}						
		return mv;
	}	
	/**
	 * 去修改页面
	 */
	@RequestMapping(value="/goEdit")
	public ModelAndView goEdit(@NotNull String peilian_id){
		logBefore(logger, "去修改Peilian页面");
		ModelAndView mv = this.getModelAndView();
		try {
			Peilian peilian =peilianService.findById(peilian_id);	//根据ID读取
			mv.setViewName("/WEB-INF/system/peilian/peilian_edit");
			mv.addObject("msg", "edit");
			mv.addObject("peilian", peilian);
		} catch (Exception e) {
			logger.error(e.toString(), e);
		}						
		return mv;
	}	
	
	@RequestMapping("choose")
	public void choose(HttpServletRequest request ,HttpServletResponse response){
		PageData pd = new PageData();		
		pd=this.getPageData();
		try {
			  response.setContentType("text/html;charset=utf-8");
			  PrintWriter out =response.getWriter();
			Timer timer=timerService.getTimerById(pd.getString("timer_id"));
			boolean b=true;
			if(timer!=null){
			if(timer.getPeilian()!=null&&timer.getPeilian().size()>0){
				for(int i=0;i<timer.getPeilian().size();i++){
					if(timer.getPeilian().get(i).getPl_id()==Integer.parseInt(pd.getString("peilian_id"))){
						b=false;
						out.print("已添加此陪练");
						out.close();
					}
				}
			}
			if(b){
				  pd.put("today", timer.getTimstr());
					peilianService.choose(pd);
					out.print("success");
					out.close();
			}
		  
			}else{
			out.print("error");
			out.close();
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}
	
	/**
	 * 批量删除
	 */
	@RequestMapping(value="/deleteAll")
	@ResponseBody
	public Object deleteAll() {
		logBefore(logger, "批量删除Peilian");
		PageData pd = new PageData();		
		Map<String,Object> map = new HashMap<String,Object>();
		try {
			pd = this.getPageData();
			List<PageData> pdList = new ArrayList<PageData>();
			String DATA_IDS = pd.getString("DATA_IDS");
			if(null != DATA_IDS && !"".equals(DATA_IDS)){
				String ArrayDATA_IDS[] = DATA_IDS.split(",");
				peilianService.deleteAll(ArrayDATA_IDS);
				pd.put("msg", "ok");
			}else{
				pd.put("msg", "no");
			}
			pdList.add(pd);
			map.put("list", pdList);
		} catch (Exception e) {
			logger.error(e.toString(), e);
		} finally {
			logAfter(logger);
		}
		return AppUtil.returnObject(pd, map);
	}
	@RequestMapping("photo")
	public ModelAndView photo(Page page){
		ModelAndView mv=new ModelAndView();
		
		PageData pd = new PageData();
		try{
			pd = this.getPageData();
			
		   this.getHC(); //调用权限
			//////////////////////////////
			Map<String,Object> map = peilianService.listPhoto(page,pd);
			page = (Page)map.get("page");
			List<Map<String,Object>> list = (List<Map<String,Object>>)map.get("list");
			mv.addObject("varList", list);
			mv.addObject("pd", pd);
			mv.addObject("page", page);
			mv.setViewName("/WEB-INF/system/peilian/photo_list");
		} catch(Exception e){
			logger.error(e.toString(), e);
		}
		
		
		return mv;
	}
	@RequestMapping("addphoto")
	public ModelAndView addphoto(){
		ModelAndView mv = this.getModelAndView();
		try {
			PageData pd=this.getPageData();
			mv.addObject("pd", pd);
			mv.setViewName("/WEB-INF/system/peilian/photo");
		} catch (Exception e) {
			logger.error(e.toString(), e);
		}						
		return mv;
	}
	
	/* ===============================权限================================== */
	@SuppressWarnings("unchecked")
	public void getHC(){
		ModelAndView mv = this.getModelAndView();
		HttpSession session = this.getRequest().getSession();
		Map<String, String> map = (Map<String, String>)session.getAttribute(Const.SESSION_QX);
		mv.addObject(Const.SESSION_QX,map);	//按钮权限
		List<Menu> menuList = (List<Menu>)session.getAttribute(Const.SESSION_menuList);
		mv.addObject(Const.SESSION_menuList, menuList);//菜单权限
	}
	/* ===============================权限================================== */
	
	@InitBinder
	public void initBinder(WebDataBinder binder){
		DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		binder.registerCustomEditor(Date.class, new CustomDateEditor(format,true));
	}
}
